﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using CCWin;
using Silkage.Helpers;
using v8sharp;
using Silkage.Public;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Newtonsoft.Json.Linq;

namespace BatchProcess
{
    public partial class FrmMain : Skin_Mac
    {
        private HttpHelpers helper = new HttpHelpers();
        private XJHTTP xJHTTP = new XJHTTP();
        private string Url = "http://imeap.cn/";
        private string Num = "166";
        private string Tid = "49";

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void Init()
        {
            Text = $"QQ名片赞每天免费领[Powered By {LocalData.Customer?.DisplayName}]";
            Icon = LocalData.Icon;
            lblQun.Click += (e, s) => { Process.Start(LocalData.Customer?.Groups.FirstOrDefault(g => g.IsMain)?.Url); };
            lblName.Text = LocalData.Customer?.DisplayName;
            lblVersion.Text = "V1.0.0";
            Url = "http://imeap.cn/";
            Num = "166";
            Tid = "49";
        }

        private string GetParam(string param)
        {
            var js = "function get(){return " + param + ";}";
            return V8Method(js, "get", "");
        }

        private string V8Method(string reString, string MethodName, string para)
        {
            V8Engine engine = V8Engine.Create();
            V8Script script = engine.Compile(reString);
            try
            {
                engine.Execute(script);
                return engine.Execute(string.Format("{0}({1})", MethodName, para)).ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private void 手动录入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmAdd = new FrmAdd();
            if (frmAdd.ShowDialog() == DialogResult.OK)
            {
                int index = dgvAccount.Rows.Add();
                dgvAccount[0, index].Value = true;
                dgvAccount[1, index].Value = frmAdd.Info;
            }
        }

        private void 粘贴导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var data = Clipboard.GetDataObject();
            if (data == null || !data.GetDataPresent(DataFormats.Text)) return;
            var dataTxt = (string)data.GetData(DataFormats.Text);
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(dataTxt);
            writer.Flush();
            stream.Position = 0;
            using (var sr = new StreamReader(stream))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    if (str.Trim() == "") continue;
                    if (!long.TryParse(str, out long qq))
                        continue;
                    int index = dgvAccount.Rows.Add();
                    dgvAccount[0, index].Value = true;
                    dgvAccount[1, index].Value = qq;
                }
            }
        }

        private void 文本导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() != DialogResult.OK)
                return;
            using (var sr = new StreamReader(openFileDialog.FileName))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    if (str.Trim() == "") continue;
                    if (!long.TryParse(str, out long qq))
                        continue;
                    int index = dgvAccount.Rows.Add();
                    dgvAccount[0, index].Value = true;
                    dgvAccount[1, index].Value = qq;
                }
            }
        }

        private void 清空账号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dgvAccount.Rows.Clear();
        }

        private void 全部选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvAccount.RowCount == 0)
                return;
            for (int i = dgvAccount.RowCount - 1; i >= 0; i--)
            {
                dgvAccount[0, i].Value = true;
            }
        }

        private void 反向选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvAccount.RowCount == 0)
                return;
            for (int i = dgvAccount.RowCount - 1; i >= 0; i--)
            {
                var flag = Convert.ToBoolean(dgvAccount[0, i].Value);
                dgvAccount[0, i].Value = !flag;
            }
        }

        private bool extractFlag;
        private void EnabledExtract()
        {
            开始查询ToolStripMenuItem.Enabled = !extractFlag;
            粘贴导入ToolStripMenuItem.Enabled = !extractFlag;
            文本导入ToolStripMenuItem.Enabled = !extractFlag;
            清空账号ToolStripMenuItem.Enabled = !extractFlag;
            全部选择ToolStripMenuItem.Enabled = !extractFlag;
            反向选择ToolStripMenuItem.Enabled = !extractFlag;
        }

        private void 开始查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvAccount.RowCount == 0)
                return;
            extractFlag = true;
            EnabledExtract();
            ThreadPool.QueueUserWorkItem(s =>
            {
                for (var i = 0; i < dgvAccount.RowCount; i++)
                {
                    if (!extractFlag)
                        return;
                    if (!Convert.ToBoolean(dgvAccount[0, i].Value))
                        continue;
                    var account = new Account
                    {
                        Qq = dgvAccount[1, i].Value?.ToString(),
                        Index = i
                    };
                    Sign(account);
                    Invoke(new MethodInvoker(delegate
                    {
                        dgvAccount[0, i].Value = false;
                    }));
                    Thread.Sleep(1000);
                }
                Invoke(new MethodInvoker(delegate
                {
                    extractFlag = false;
                    EnabledExtract();
                }));
            });
        }

        private void Sign(Account account)
        {
            var msg = "领取异常,请稍后重试";
            try
            {
                var cookie = "";
                var item = new HttpItems
                {
                    URL = Url,
                    Cookie = cookie
                };
                var res = helper.GetHtml(item, ref cookie).Html;
                var regex = new Regex("setCookie\\('sec_defend',([\\s\\S]*?)\\);setCookie");
                var sec_defend = regex.Match(res).Groups[1].Value;
                sec_defend = GetParam(sec_defend);
                cookie += $";sec_defend={sec_defend};";
                item = new HttpItems
                {
                    URL = Url,
                    Cookie = cookie
                };
                res = helper.GetHtml(item, ref cookie).Html;
                var hashsalt = xJHTTP.GetMidHtml(res, "hashsalt=", ";");
                hashsalt = GetParam(hashsalt);
                item = new HttpItems
                {
                    URL = $"{Url}ajax.php?act=pay",
                    Method = "POST",
                    Postdata = $"tid={Tid}&inputvalue={account.Qq}&num=1&hashsalt={hashsalt}",
                    Cookie = cookie
                };
                res = helper.GetHtml(item, ref cookie).Html;
                var obj = JObject.Parse(res);
                if (obj.Property("need") == null || obj.Property("need").ToString() == "")
                {
                    msg = $"恭喜您,成功领取{Num}个名片赞";
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            Invoke(new MethodInvoker(delegate
            {
                dgvAccount[2, account.Index].Value = msg;
            }));
        }

        private void 暂停查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            extractFlag = false;
            EnabledExtract();
        }
    }

    public class Account
    {
        public string Qq { get; set; }
        public int Index { get; set; }
    }
}
